/**
    @author: dt
    @date: 2025-06-23
    @description: 行为树构建器
*/

using System.Collections.Generic;
using UnityEngine;
using DLib.BehaviorTree.Tasks;

namespace DLib.BehaviorTree
{
    /// <summary>
    /// 行为树构建器
    /// 提供流畅的API来构建复杂的行为树
    /// 支持链式调用和嵌套结构
    /// </summary>
    public class BehaviorTreeBuilder
    {
        /// <summary>当前正在构建的根节点</summary>
        private Node currentNode;
        
        /// <summary>节点栈，用于管理嵌套结构</summary>
        private Stack<Node> nodeStack = new Stack<Node>();

        /// <summary>
        /// 构造函数
        /// 初始化节点栈
        /// </summary>
        public BehaviorTreeBuilder()
        {
            nodeStack.Push(null); // 根节点占位符
        }

        /// <summary>
        /// 开始构建选择器节点
        /// 选择器实现OR逻辑，只要有一个子节点成功就返回成功
        /// </summary>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Selector()
        {
            Selector selector = new Selector();
            AddToCurrentNode(selector);
            nodeStack.Push(selector);
            return this;
        }

        /// <summary>
        /// 开始构建选择器节点（带选项）
        /// </summary>
        /// <param name="alwaysStartFromBeginning">是否每次从头开始运行（用于中断机制）</param>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Selector(bool alwaysStartFromBeginning)
        {
            Selector selector = new Selector();
            selector.SetAlwaysStartFromBeginning(alwaysStartFromBeginning);
            AddToCurrentNode(selector);
            nodeStack.Push(selector);
            return this;
        }

        /// <summary>
        /// 开始构建序列节点
        /// 序列实现AND逻辑，所有子节点都成功才返回成功
        /// </summary>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Sequence()
        {
            Sequence sequence = new Sequence();
            AddToCurrentNode(sequence);
            nodeStack.Push(sequence);
            return this;
        }

        /// <summary>
        /// 添加反转装饰器
        /// 反转装饰器将子节点的结果反转（成功变失败，失败变成功）
        /// </summary>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Inverter()
        {
            Inverter inverter = new Inverter(null); // 临时占位符
            AddToCurrentNode(inverter);
            nodeStack.Push(inverter);
            return this;
        }

        /// <summary>
        /// 添加重复装饰器
        /// 重复装饰器重复执行子节点指定次数
        /// </summary>
        /// <param name="repeatCount">重复次数，-1表示无限重复</param>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Repeater(int repeatCount = -1)
        {
            Repeater repeater = new Repeater(null, repeatCount); // 临时占位符
            AddToCurrentNode(repeater);
            nodeStack.Push(repeater);
            return this;
        }

        /// <summary>
        /// 添加日志任务
        /// 在控制台输出指定的消息
        /// </summary>
        /// <param name="message">要输出的消息</param>
        /// <param name="delay">延迟时间（秒）</param>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Log(string message, float delay = 0f)
        {
            AddToCurrentNode(new LogTask(message, delay));
            return this;
        }

        /// <summary>
        /// 添加等待任务
        /// 等待指定的时间
        /// </summary>
        /// <param name="time">等待时间（秒）</param>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Wait(float time)
        {
            AddToCurrentNode(new WaitTask(time));
            return this;
        }

        /// <summary>
        /// 添加随机任务
        /// 根据概率返回成功或失败
        /// </summary>
        /// <param name="probability">成功概率（0-1之间）</param>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Random(float probability = 0.5f)
        {
            AddToCurrentNode(new RandomTask(probability));
            return this;
        }

        /// <summary>
        /// 添加自定义任务节点
        /// </summary>
        /// <param name="task">自定义任务节点</param>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder Task(TaskNode task)
        {
            AddToCurrentNode(task);
            return this;
        }

        /// <summary>
        /// 结束当前节点
        /// 从节点栈中弹出当前节点，表示该节点构建完成
        /// </summary>
        /// <returns>构建器实例，支持链式调用</returns>
        public BehaviorTreeBuilder End()
        {
            if (nodeStack.Count > 1)
            {
                Node completedNode = nodeStack.Pop();
                Node parentNode = nodeStack.Peek();
                
                // 处理装饰器的嵌套情况
                if (completedNode is DecoratorNode decorator && parentNode is DecoratorNode parentDecorator)
                {
                    // 简化实现：直接添加到父装饰器的父节点
                    if (nodeStack.Count > 2)
                    {
                        Node grandParent = nodeStack.ToArray()[nodeStack.Count - 2];
                        if (grandParent is CompositeNode composite)
                        {
                            composite.AddChild(completedNode);
                        }
                    }
                }
            }
            return this;
        }

        /// <summary>
        /// 构建完成，返回根节点
        /// </summary>
        /// <returns>构建完成的行为树根节点</returns>
        public Node Build()
        {
            if (nodeStack.Count > 1)
            {
                Debug.LogWarning("BehaviorTreeBuilder: 还有未结束的节点");
            }
            
            return currentNode;
        }

        /// <summary>
        /// 将节点添加到当前节点
        /// 根据当前节点类型决定如何添加子节点
        /// </summary>
        /// <param name="node">要添加的节点</param>
        private void AddToCurrentNode(Node node)
        {
            if (currentNode == null)
            {
                // 第一个节点作为根节点
                currentNode = node;
            }
            else if (nodeStack.Peek() is CompositeNode composite)
            {
                // 复合节点可以添加多个子节点
                composite.AddChild(node);
            }
            else if (nodeStack.Peek() is DecoratorNode decorator)
            {
                // 装饰器只能有一个子节点
                if (decorator.GetChildren().Count == 0)
                {
                    decorator.AddChild(node);
                }
            }
        }

        /// <summary>
        /// 便捷方法：创建简单的选择器
        /// </summary>
        /// <param name="children">子节点数组</param>
        /// <returns>选择器节点</returns>
        public static Node CreateSelector(params Node[] children)
        {
            return new Selector(new List<Node>(children));
        }

        /// <summary>
        /// 便捷方法：创建简单的序列
        /// </summary>
        /// <param name="children">子节点数组</param>
        /// <returns>序列节点</returns>
        public static Node CreateSequence(params Node[] children)
        {
            return new Sequence(new List<Node>(children));
        }

        /// <summary>
        /// 便捷方法：创建带反转的节点
        /// </summary>
        /// <param name="child">子节点</param>
        /// <returns>反转装饰器节点</returns>
        public static Node CreateInverter(Node child)
        {
            return new Inverter(child);
        }

        /// <summary>
        /// 便捷方法：创建带重复的节点
        /// </summary>
        /// <param name="child">子节点</param>
        /// <param name="repeatCount">重复次数</param>
        /// <returns>重复装饰器节点</returns>
        public static Node CreateRepeater(Node child, int repeatCount = -1)
        {
            return new Repeater(child, repeatCount);
        }
    }
} 